package com.example.servlet;

import com.example.bean.User;
import com.example.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录处理Servlet
 * 使用JSP + Servlet + JavaBean架构
 * Servlet作为控制器，调用Service层（JavaBean）处理业务逻辑
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    // 使用Service层（JavaBean）而不是直接使用DAO
    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // GET请求直接转发到登录页面
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // 获取表单参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String verifyCode = request.getParameter("verifyCode");

        // 获取session
        HttpSession session = request.getSession();

        // 1. 验证输入是否为空
        if (username == null || username.trim().isEmpty()) {
            request.setAttribute("error", "用户名不能为空！");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }

        if (password == null || password.trim().isEmpty()) {
            request.setAttribute("error", "密码不能为空！");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }

        if (verifyCode == null || verifyCode.trim().isEmpty()) {
            request.setAttribute("error", "验证码不能为空！");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }

        // 2. 验证验证码
        String sessionCode = (String) session.getAttribute("verifyCode");
        Long codeTime = (Long) session.getAttribute("verifyCodeTime");

        if (sessionCode == null) {
            request.setAttribute("error", "验证码已过期，请刷新验证码！");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }

        // 验证码5分钟有效期
        if (codeTime != null && (System.currentTimeMillis() - codeTime) > 5 * 60 * 1000) {
            request.setAttribute("error", "验证码已过期，请刷新验证码！");
            session.removeAttribute("verifyCode");
            session.removeAttribute("verifyCodeTime");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }

        // 验证码不区分大小写
        if (!sessionCode.equalsIgnoreCase(verifyCode.trim())) {
            request.setAttribute("error", "验证码错误！");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }

        // 验证码验证成功后立即删除，防止重复使用
        session.removeAttribute("verifyCode");
        session.removeAttribute("verifyCodeTime");

        // 3. 验证用户名和密码（调用Service层JavaBean）
        User user = userService.login(username.trim(), password.trim());

        if (user == null) {
            request.setAttribute("error", "用户名或密码错误！");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }

        // 4. 登录成功，将用户信息存入session
        session.setAttribute("currentUser", user);
        session.setAttribute("username", user.getUsername());
        session.setAttribute("role", user.getRole());

        // 5. 根据用户角色跳转到不同页面
        if (user.isAdmin()) {
            // 管理员跳转到管理员页面
            response.sendRedirect(request.getContextPath() + "/admin.jsp");
        } else {
            // 普通用户跳转到用户页面
            response.sendRedirect(request.getContextPath() + "/user.jsp");
        }
    }
}

